<?php

namespace App\Livewire;

use App\Models\ArticleAction;
use App\Models\ArticleAction as ArticleActionModel;
use Carbon\Carbon;
use Livewire\Attributes\Title;
use Livewire\Component;
use App\Models\Article as ArticleModel;

class Article extends Component
{

    public $article;

    public function mount($id)
    {
        $this->article = ArticleModel::query()->find($id);
        if ($this->getRecord(request()->ip(), 'view')) {
            $this->article->increment('reading_quantity');
            ArticleAction::query()->create([
                'article_id' => $id,
                'ip'         => request()->ip(),
                'type'       => 'view',
            ]);
        }
    }

    public function getRecord($ip, $type)
    {
        $record = ArticleActionModel::query()
            ->where('ip', $ip)
            ->where('type', $type)
            ->whereDay('created_at', Carbon::today())
            ->first();
        if (is_null($record)) {
            return true;
        }
    }

    #[Title('文章')]
    public function render()
    {
        return view('livewire.article', [
            'article' => $this->article
        ]);
    }
}
